package neichuan.center;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import neichuan.message.Message;
import neichuan.message.MessageHeaderFiled;
import neichuan.message.MessageType;
import neichuan.util.config.DefaultConfig;

import java.util.concurrent.ConcurrentLinkedQueue;

public class ExchangeCenter {
    //与客户端一直维持连接的通道
    Channel mainChannel;
    //与客户端临时交流的通道
//    ConcurrentLinkedQueue<Channel> availableChannels=new ConcurrentLinkedQueue();

    //浏览器最大连接数
    int browserChannelsMax= Integer.valueOf(DefaultConfig.getConfig(DefaultConfig.Field.BROWSER_SERVER_CONNECTION_COUNT));
    //与浏览器连接的通道
    ConcurrentLinkedQueue<Channel> browserChannels=new ConcurrentLinkedQueue();
    Object addBrowserChannelLock=new Object();

    Channel browserServerChannel;

    //synchronized
    /**
     * 没有通道返回null
     * @return
     */
    public Channel getBrowserChannel() {
        if(browserChannels.isEmpty()){
            return null;
        }
        return browserChannels.remove();
    }

    //synchronized
    /**
     * 添加浏览器通道，如果查过最大连接数，则不允许放入
     * @param browserChannel
     * @return
     */
    public boolean addBrowserChannel(Channel browserChannel){
        System.out.println(browserChannel.remoteAddress()+"|"+browserChannel.localAddress()+"被放入通道");
        if(browserChannels.size() >= browserChannelsMax){
            return false;
        }
        synchronized (addBrowserChannelLock) {
            if (browserChannels.size() < browserChannelsMax) {
                browserChannels.add(browserChannel);
            }
        }
        return true;

    }


    public ExchangeCenter(){

    }

    public ExchangeCenter(Channel mainChannel){
        registMainChannel(mainChannel);
    }

    /**
     * 注册主通道，该通道一直维持连接
     * @param mainChannel
     * @return
     */
    public void registMainChannel(Channel mainChannel){
        this.mainChannel=mainChannel;
    }


    public void addBrowserServerChannel(Channel browserServerChannel){
        this.browserServerChannel=browserServerChannel;
    }

    /**
     * 关闭所有通道
     */
    public void close(){
        if(mainChannel!=null){
            mainChannel.close();
        }
        if(browserServerChannel!=null){
            browserServerChannel.close();
        }
        if(browserChannels!=null){
            browserChannels.forEach(ch->{ch.close();});
        }

    }

    //synchronized
    /**
     * 通知创建一个临时客户端Channel
     */
    public void createNewChannel(int port){
        ByteBuf byteBuf=mainChannel.alloc().buffer();
        Message message=new Message(MessageType.REQUEST_CREATE_TEMP_CONNECTION,null,null);
        message.setHeader(MessageHeaderFiled.PORT,String.valueOf(port));
        mainChannel.writeAndFlush(message);
    }



    public Channel getMainChannel(){
        return mainChannel;
    }
}
